package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.util.JsonResult;
import cn.wolfcode.luowowo.util.Md5Utils;
import com.alibaba.fastjson.JSON;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class SignInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //签名验证
        Map<String, String[]> map = request.getParameterMap();
        Set<String> keys = map.keySet();
        Map<String, Object> param = new HashMap<>();
        for (String s : keys) {
            if("sign".equalsIgnoreCase(s)){
                continue;
            }
            param.put(s,arrayToString(map.get(s)));
        }
        //后端将传过来的参数除sign外进行加密
        String signatures = Md5Utils.signatures(param);
        //获取前端传来的sign，然后两者进行比对
        String sign = request.getParameter("sign");
        if(sign==null || !sign.equalsIgnoreCase(signatures)){
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(new JsonResult<>(501,"签名失效或错误","请重试")));
            return false;
        }
        return true;
    }

    private String arrayToString(String[] strings) {
        StringBuilder sb = new StringBuilder(10);
        for (String string : strings) {
            sb.append(string);
        }
        return sb.toString();

    }
}
